﻿/****************************************************************************************************
	Copyright (C) 2010 RapidWebDev Organization (http://rapidwebdev.org)
	Author: Eunge, Legal Name: Jian Liu, Email: eunge.liu@RapidWebDev.org

	The GNU Library General Public License (LGPL) used in RapidWebDev is 
	intended to guarantee your freedom to share and change free software - to 
	make sure the software is free for all its users.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Library General Public License (LGPL) for more details.

	You should have received a copy of the GNU Library General Public License (LGPL)
	along with this program.  
	If not, see http://www.rapidwebdev.org/Content/ByUniqueKey/OpenSourceLicense
 ****************************************************************************************************/

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Xml;
using System.Xml.Serialization;
using RapidWebDev.Common;

namespace RapidWebDev.Common.WikiContent.Impl
{
	/// <summary>
	/// The implementation of content rendering configuration Api.
	/// </summary>
	public class ContentRenderingConfigApi : IContentRenderingConfigApi
	{
		private static readonly XmlSerializer xmlSerializer = new XmlSerializer(typeof(ContentRenderingConfig));
		private string contentRenderingConfigDirectory;

		private Dictionary<string, ContentRenderingConfig> ContentRenderingConfigDictionary
		{
			get
			{
				const string cacheKey = "ContentRenderingConfigApi::ContentRenderingConfigDictionary";
				Dictionary<string, ContentRenderingConfig> contentRenderingConfigDictionary = null;
				if (HttpContext.Current != null)
				{
					contentRenderingConfigDictionary = HttpContext.Current.Cache[cacheKey] as Dictionary<string, ContentRenderingConfig>;
					if (contentRenderingConfigDictionary != null) return contentRenderingConfigDictionary;
				}

				contentRenderingConfigDictionary = ResolveContentRenderingConfigs(this.contentRenderingConfigDirectory);
				if (HttpContext.Current != null)
					HttpContext.Current.Cache.Add(cacheKey, contentRenderingConfigDictionary, null, Cache.NoAbsoluteExpiration, new TimeSpan(1, 0, 0), CacheItemPriority.Default, null);

				return contentRenderingConfigDictionary;
			}
		}

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="contentRenderingConfigDirectory">The directory of the configuration files for rendering content.</param>
		public ContentRenderingConfigApi(string contentRenderingConfigDirectory)
		{
			Kit.NotNull(contentRenderingConfigDirectory, "contentRenderingConfigDirectory");
			this.contentRenderingConfigDirectory = contentRenderingConfigDirectory;
		}

		/// <summary>
		/// Resolve content rendering configuration by id.
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public ContentRenderingConfig Resolve(string id)
		{
			if (this.ContentRenderingConfigDictionary.ContainsKey(id))
				return this.ContentRenderingConfigDictionary[id];

			return null;
		}

		private Dictionary<string, ContentRenderingConfig> ResolveContentRenderingConfigs(string contentRenderingConfigDirectory)
		{
			contentRenderingConfigDirectory = Kit.ToAbsolutePath(contentRenderingConfigDirectory);

			if (!Directory.Exists(contentRenderingConfigDirectory))
				return new Dictionary<string, ContentRenderingConfig>(StringComparer.OrdinalIgnoreCase);

			Dictionary<string, ContentRenderingConfig> returnValue = new Dictionary<string, ContentRenderingConfig>(StringComparer.OrdinalIgnoreCase);
			string[] contentRenderingConfigFiles = Directory.GetFiles(contentRenderingConfigDirectory, "*.xml", SearchOption.AllDirectories);
			foreach (string contentRenderingConfigFile in contentRenderingConfigFiles)
			{
				using (XmlReader xmlReader = XmlReader.Create(contentRenderingConfigFile))
				{
					ContentRenderingConfig contentRenderingConfig = xmlSerializer.Deserialize(xmlReader) as ContentRenderingConfig;
					if (contentRenderingConfig == null)
						throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, "The content rendering configuration file \"{0}\" is invalid.", contentRenderingConfigFile));

					if (returnValue.ContainsKey(contentRenderingConfig.Id))
						throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, "The id \"{1}\" of content rendering configuration file \"{0}\" is duplicate.", contentRenderingConfigFile, contentRenderingConfig.Id));

					returnValue[contentRenderingConfig.Id] = contentRenderingConfig;
				}
			}

			return returnValue;
		}
	}
}